<template>
  <div class="login">
    <h2>Login</h2>
    <form @submit.prevent="handleLogin">
      <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" id="username" v-model="username" required />
      </div>
      <div class="form-group">
        <label for="password">Password:</label>
        <input type="password" id="password" v-model="password" required />
      </div>
      <button type="submit">Login</button>
      <p v-if="error" class="error">{{ error }}</p>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Login',
  data() {
    return {
      username: '',
      password: '',
      error: null,
    };
  },
  methods: {
    async handleLogin() {
      try {
        const response = await axios.post('http://localhost:8080/login', {
          username: this.username,
          password: this.password,
        });
        const token = response.data;
        // 将JWT令牌存储在本地存储中
        localStorage.setItem('jwtToken', token);
        localStorage.setItem('username', this.username);
        //返回主页
        this.$router.push('/');
      } catch (error) {
        if (error.response && error.response.status === 401) {
          this.error = 'Invalid credentials';
        } else {
          this.error = 'An error occurred during login';
        }
      }
    },
  },
};
</script>

<style scoped>
.login {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.form-group {
  margin-bottom: 15px;
}

.error {
  color: red;
}
</style>